/**
 * 分段专题图
 * 说明：可选择分段算法、分段数目、分段颜色
 */
// console.log(rangeThemeLayer.container.id);
import sgisLayerBase from '../../sfgis.layer.base';
import sgisSpatialQuery from "../../sfgis.spatial.query";
import dataAnalysis from "../../sfgis.data.analysis";
import styleModify from "./echarts.stylemodify"; // 为图层设置透明度，可见性，zIndex而设置
import store from "../../../../pages/macro/store";
import { getMapLayers } from "vuex";
export default {
    layerNum: 0,
    // 默认配色方案  默认分为5段
    popup: "",
    rangeThemeLayer: "",
    options:{},
    rangeThemeLayerInfo: {},
    themeField: "POP_DENSITY99",
    featureData: {},
    map: "",
    styleGroups: [],
    segment_values: "",
    callbackLayer: '',

    /**
     * {
          id:"",  // 图层id
          name:"",   // 图层名称
          datas:[    //数据支持多年数据展示
            {
              segment_values:[],  // 图层分段值
              values:[{"regioncode":"","rname":"","regiontype":"","value":"",},{}]
            }  // 数值信息
          ]
     * }
     * @param {Object} map 地图对象
     * @param {Object} data  出图参数
     */
    createLayer(map, data, callbackLayer) {
        this.map = map;
        this.segment_values = data.datas[0].segment_values
        this.callbackLayer = callbackLayer;
        let popup;
        let segment_values_temp = dataAnalysis.themerange.getSegmentByDataArr(
            data.datas[0].all_segment_values,
            5
        );

        let rangeThemeLayerColor = this.getStyleGroups(segment_values_temp);
        this.styleGroups = rangeThemeLayerColor;
        let currentCode = "";
        let rangeThemeLayer = new mapboxgl.supermap.RangeThemeLayer("rangeThemeLayer",
            {
                //                map: map,//该可选参数将在下个版本遗弃
                attributions: " ",
                opacity: 0.8,
                id: "rangeThemeLayer" + +new Date(),
                style: {
                    shadowBlur: 16,
                    shadowColor: "#000000",
                    fillColor: "#FFFFFF"
                },
                isHoverAble: true,
                highlightStyle: {
                    stroke: true,
                    strokeWidth: 4,
                    strokeColor: 'blue',
                    fillColor: "#00EEEE",
                    fillOpacity: 0.8
                },
                themeField: "POP_DENSITY99",
                styleGroups: []
            });
        rangeThemeLayer.options = {
            ...rangeThemeLayer.options,
            ...this
        }; // 自定义设置颜色时用到参数设置
        this.rangeThemeLayer = rangeThemeLayer
        rangeThemeLayer.styleGroups = rangeThemeLayerColor;
        rangeThemeLayer.options.styleGroups = rangeThemeLayerColor
        rangeThemeLayer.type = "rangeThemeLayer"

        // 分段风格数组
        rangeThemeLayer.styleGroups = rangeThemeLayerColor;
        rangeThemeLayer.rangeThemeLayer = rangeThemeLayer
        // map.addLayer(rangeThemeLayer.rangeThemeLayer)
        let layerid = 'rangeThemeLayer';
        // 用于专题图的值得字段名称
        rangeThemeLayer.themeField = "value";
        rangeThemeLayer.layerId = layerid;
        //设置高亮图层提示
        this.addFeatures(data.datas[0].values, rangeThemeLayer, map);

        // 为rangeThemeLayer 注册修改color的方法
        rangeThemeLayer.setCustomColor = this.setCustomColor;
        // 将数据绑定到图层，方便刷新图层

        rangeThemeLayer.setOpacity = this.setOpacity; // 设置图层透明度
        rangeThemeLayer.getStyleGroups = this.getStyleGroups; // 设置图层透明度
        // rangeThemeLayer.layerId = layerid;

        // 绑定鼠标进入时间
        // rangeThemeLayer.on("mousemove", this.showInfoWin);
        // rangeThemeLayer.on("mouseout", this.closeInfoWin);
        rangeThemeLayer.setZIndexOffset = this.setZIndexOffset; // 设置图层顺序函数
        // rangeThemeLayer.container.style.zIndex = styleModify.curZindex; // 为设置图层顺序调整特意设置
        styleModify.layerOrder[layerid] = styleModify.curZindex;
        rangeThemeLayer.options.currdata = data.datas[0]; // 当前数据
        styleModify.curZindex -= 1;
        rangeThemeLayer.setVisible = this.setVisible; // 设置图层可见性
        // 保存一下图层信息
        this.rangeThemeLayerInfo = {
            // 要保证此id和rangeThemeLayer的option中的id一致，此处只有根据元素id获得layer
            layerId: 'rangeThemeLayer',
            name: data.name,
            show: data.showThumbnails !== false,
            type: 'rangeThemeLayer',
            html: this.calgraph('rangeThemeLayer', rangeThemeLayerColor, 'auto')
        };
        store.commit("getMapLayers", this.rangeThemeLayerInfo)
        map.overlayers["rangeThemeLayer"] = rangeThemeLayer
        map.overlayerInfos["rangeThemeLayer"] = this.rangeThemeLayerInfo;

        sgisLayerBase.setOverLayers(this.rangeThemeLayerInfo);
        // //设置高亮图层提示
        // this.addFeatures(data.datas[0].values,rangeThemeLayer,map);
        return this.rangeThemeLayerInfo;
    },
    addFeatures(values, layer, map) {
        let valueTemp = {};
        let regioninfos = [];
        for (let i = 0; i < values.length; i++) {
            // 每一百个区划叠加一次，不一次性查询出来，村的边界数据太大
            let regioncode = values[i].regioncode;
            let value = values[i].value;
            let regiontype = values[i].regiontype;
            valueTemp[regioncode] = value;
            let regionInfo = {
                regioncode: regioncode,
                regiontype: regiontype
            };
            regioninfos.push(regionInfo);
            if (i > 0 && i % 100 === 0) {
                this.queryFeatures(valueTemp, regioninfos, layer, map);
                valueTemp = {};
                regioninfos = [];
            }
        }
        if (valueTemp !== null && !$.isEmptyObject(valueTemp)) {
            this.queryFeatures(valueTemp, regioninfos, layer, map);
        }
    },
    queryFeatures(data, regioninfos, rangeThemeLayer, map) {
        let that = this;
        let regiontype = regioninfos[0].regiontype;
        sgisSpatialQuery.spatialQueryUtil.getFeaturesByRegionCodes(
            regioninfos,
            regiontype,
            (serviceResult) => {
                that.callbackLayer();//一切执行完毕，才能执行回掉
                let result = serviceResult.result;
                if (result && result.features) {
                    let features = result.features;
                    // rangeThemeLayer.addFeatures();
                    // 重新构造一下features
                    for (let i = 0; i < features.features.length; i++) {
                        let code = features.features[i].properties.QH_CODE;
                        features.features[i].properties["value"] = data[code];
                    }
                    map.addLayer(rangeThemeLayer)
                    rangeThemeLayer.addFeatures(features.features);
                    let popup;
                    let currentCode;
                    
                    rangeThemeLayer.on('mousemove', function (e) {
                        if (e.target && e.target.refDataID) {
                            var fid = e.target.refDataID;
                            var fea = rangeThemeLayer.getFeatureById(fid);
                            if (fea) {
                                if (!popup) {
                                    popup = new mapboxgl.Popup({
                                        anchor: 'bottom',
                                        closeButton: false,
                                        offset: {
                                            'bottom': [0, -10],
                                        }
                                    });
                                }
                                
                                let innerHtml = `<span>区划名称：${fea.data.NAME}</span></br><span>${store.state.macro.currentIdenName['rangeThemeLayer']}：${fea.data.value}</span>`
                                popup.setHTML(innerHtml);
                                popup.setLngLat([fea.geometry.bounds.centerLonLat.lon,fea.geometry.bounds.centerLonLat.lat]);
                                popup.addTo(map);
                                currentCode = fea.data.QH_CODE
                                EventBus.$emit("onChart-action", { regionCode: fea.data.QH_CODE });
                                EventBus.$emit("table-actiontrigger", {
                                    regionCode: fea.data.QH_CODE
                                });
                            }
                        }
                        else {
                            if(popup){
                                popup.remove();
                                EventBus.$emit("offChart-action", { regionCode: currentCode });
                                EventBus.$emit("table-heighLightOff", { regionCode: currentCode });
                            }
                        }
                    });
                    rangeThemeLayer.on('mouseout',function(){
                        if(popup){
                            popup.remove();
                            EventBus.$emit("offChart-action", { regionCode: currentCode });
                            EventBus.$emit("table-heighLightOff", { regionCode: currentCode });
                        }
                    })
                }
            }
        );
    },
    setCustomColor(layer, colorParam) {
        let currStyleGroups = layer.styleGroups;
        /**
         * 判断颜色长度是否变化是否需要重新分段，
         * 1、如果分段数不变则直接调整颜色，重绘图层就可以
         * 2、如果分段数目发生改变则需要重新调整数据分段
         */
        const len = colorParam.colors.length;
        let colorsList = [];
        colorParam.colors.map((item,index)=>{
            colorsList.push(item.split("#")[1])
        })
        this.options.colors = colorParam.colors;
        store.commit("keepRangeThemeLayerColor", colorsList)
        if (currStyleGroups.length === len) {
            currStyleGroups = layer.styleGroups;
            for (let i = 0; i < currStyleGroups.length; i++) {
                currStyleGroups[i].style.color = colorParam.colors[i];
            }
        } else {
            // 重新调整分段数目，获取新的styleGroups
            let dataTemp = layer.options.currdata.all_segment_values;
            let segment_values_temp = dataAnalysis.themerange.getSegmentByDataArr(
                dataTemp,
                len
            ); // 这个地方要根据data重新获取
            layer.options.currdata.segment_values = segment_values_temp;
            currStyleGroups = layer.getStyleGroups(segment_values_temp);
        }
        layer.styleGroups = currStyleGroups;
        this.options.calgraph(layer.layerId, layer.styleGroups, 'auto'); // 更新图例
        layer.redrawThematicFeatures()
    },
    hexToRgb(hex) {
        if (hex == "transparent") {
            return [0, 0, 0]
        }
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? [
            parseInt(result[1], 16),
            parseInt(result[2], 16),
            parseInt(result[3], 16)] : null;
    },
    /**
   * 刷新图层样式
   */
    refreshStyles(styleGroups, layer) {
        layer.styleGroups = styleGroups;
        layer.options.styleGroups = styleGroups
        layer.update();
    },
    /**
     * 设置图层可见性
     */
    setVisible(visible) {
        if (document.getElementById(this.id)) {
            document.getElementById(this.id).style.visibility = visible;
        }
    },
    setZIndexOffset(index) {
        styleModify.setZIndexOffset(index, this.layerId, this.canvas);
    },
    getStyleGroups(segment_values) {
        let color = store.state.macro.rangeThemeLayerColor;
        if (this.rangeThemeLayer.options && this.rangeThemeLayer.options.colors) {
            color = [];
            for (const item of this.rangeThemeLayer.options.colors) {
                const value = item.slice(1);
                color.push(value);
            }
        }
        // if (this.colors.length > 0) {
        //   color = this.colors[0];
        //   this.colors.splice(0, 1);
        // }
        let styleGroups = [];
        /**
         * 前后端分别用 -999999999999999999999999999   999999999999999999999999999
         * 保证覆盖到所有的值
         */
        for (let i = 0; i < segment_values.length; i++) {
            let style = {
                start: i === 0 ? -999999999999999999999999999 : parseInt(segment_values[i - 1]),
                end: i === segment_values.length - 1 ?
                    999999999999999999999999999 : parseInt(segment_values[i]),
                style: {
                    color: i === 0 ? getLightColor("#" + color[0], 0.5) : "#" + color[i - 1]
                }
            };
            styleGroups.push(style);
        }
        //hex颜色转rgb颜色
        function HexToRgb(str) {
            var r = /^\#?[0-9A-F]{6}$/;
            //test方法检查在字符串中是否存在一个模式，如果存在则返回true，否则返回false
            if (!r.test(str)) return window.alert("输入错误的hex");
            //replace替换查找的到的字符串
            str = str.replace("#", "");
            //match得到查询数组
            var hxs = str.match(/../g);
            //alert('bf:'+hxs)
            for (var i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
            //alert(parseInt(80, 16))
            //console.log(hxs);
            return hxs;
        }
        //GRB颜色转Hex颜色
        function RgbToHex(a, b, c) {
            var r = /^\d{1,3}$/;
            if (!r.test(a) || !r.test(b) || !r.test(c)) return window.alert("输入错误的rgb颜色值");
            var hexs = [a.toString(16), b.toString(16), c.toString(16)];
            for (var i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = "0" + hexs[i];
            return "#" + hexs.join("");
        }
        function getLightColor(color, level) {
            var r = /^\#?[0-9A-F]{6}$/;
            if (!r.test(color)) return window.alert("输入错误的hex颜色值");
            var rgbc = HexToRgb(color);
            for (var i = 0; i < 3; i++) rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i]);
            return RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
        }
        return styleGroups;
    },
    // 循环去取颜色，防止两次出图时颜色一样
    /* *设置图层透明度 */
    setOpacity(opacity) {
    },
    /* *图例样式计算 */
    calgraph(layerId, styleGroup, auto) {
        let html = `
     <div class="${layerId} chart_item" style='padding:6px;'>
        <ul style='padding:0;margin:0'>
    `;
        for (const key in styleGroup) {
            const item = styleGroup[key];
            html += `<li style='list-style:none;padding:5px 0;display:${item.start == item.end || item.end == 0 ? 'none' : 'block'}'>`;
            if (key === "0") {
                html += `<div style='display:flex;align-items: center;'><div style='display:inline-block;width:10px;height:10px;background:${item.style.color}'>
        </div><p style="color:#fff">&nbsp;&nbsp;&nbsp;&nbsp;<&nbsp;${item.end}</p></div>`;
            } else if (key === styleGroup.length - 1 + "") {
                html += `<div style='display:flex;align-items: center;'><div style='display:inline-block;width:10px;height:10px;background:${item.style.color}'>
        </div><p style="color:#fff">&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;${item.start == 0 ? store.state.macro.currentIdenThemanger : item.start}</p>`
                    ;
            } else {
                html += `<div style='display:flex;align-items: center;'><div style='display:inline-block;width:10px;height:10px;background:${item.style.color}'>
        </div><p style="color:#fff"><span>&nbsp;&nbsp;&nbsp;&nbsp;${item.start}</span>
        &nbsp;-&nbsp;<span>${item.end}</span></p>`;
            }
            html += `</li>`;
        }
        html += `</ul>
     </div>`;
        if (auto === 'auto') {
            const layers = sgisLayerBase.overLayers;
            for (const key in layers) {
                if (layers[key].layerId === layerId) {
                    layers[key].html = html;
                }
            }
        }
        return html;
    },
};
